package com.sea.base.activities

import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.viewbinding.ViewBinding
import com.sea.base.ext.global.logE
import com.sea.base.start.StartActivityForResultHelper
import com.sea.base.ui.IUIContext
import com.sea.base.utils.BaseParamsUtils
import com.sea.base.utils.ViewBindingHelper

/**
 *  基类activity kotlin版
 *  @param T 见[vb]，如果真的不想使用，可以直接写[ViewBinding]（此时不能使用[vb]）
 */
abstract class BaseKtActivity<T : ViewBinding> : AutoIUIActivity() {

    internal var _vb: T? = null
    protected val vb get() = _vb ?: throw IllegalStateException("请不要在super.onCreate前调用或者没有正确的泛型T")
    protected val hasVb get() = _vb != null

    protected var newIntent: Intent? = null
        private set

    /**
     * 当前最新的intent
     */
    protected val currentIntent: Intent
        get() {
            newIntent?.let { return it }
            return intent
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        val state = if (supportRebuildData()) savedInstanceState else null
        super.onCreate(state)

        if (StartActivityForResultHelper.isCallbackAndRebuild(intent)) {
            //是回调式跳转并且被重建了，此时应该关闭当前页面，以防止出现操作无效的情况
            "基于回调式的result不支持页面重建，所以关闭当前页面$this".logE()
            finish()
            return
        }

        val vbClass = ViewBindingHelper.getViewBindingClass<T>(javaClass)
            ?: throw IllegalArgumentException("没有找到类${this}的ViewBinding，请检查")
        if (vbClass != ViewBinding::class.java) {
            _vb = ViewBindingHelper.getViewBindingInstance(this, layoutInflater, null)
        }

        if (openAutoBindParams()) {
            BaseParamsUtils.initWithActivity(this, intent)
        }

        onPagerBindViewPrepare()

        setContentViewByBase()

        init(state)
        bindData()
    }

    protected open fun setContentViewByBase() {
        if (_vb != null) {
            setContentView(vb.root)
        }
    }

    @Deprecated(
        "和重建差不多，persistentState是可以保留到系统重启后，当然你必须要单独做好适配",
        ReplaceWith("super.onCreate(savedInstanceState)")
    )
    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
    }

    override fun onNewIntent(intent: Intent?) {
        newIntent = intent
        super.onNewIntent(intent)
        //此intent中可能存在逻辑分叉点，暂不提供参数自动覆盖，否则容易导致隐式逻辑
        //如有需要自行重写调用：reInitNewIntentParams
    }

    protected fun reInitNewIntentParams() {
        BaseParamsUtils.initWithActivity(this, newIntent)
    }

    @RequiresApi(9999)
    @Deprecated("请不要随意修改intent", ReplaceWith("currentIntent、newIntent"))
    override fun setIntent(newIntent: Intent?) {
        super.setIntent(newIntent)
    }

    @Deprecated("见addBackPressedCallback", ReplaceWith("addBackPressedCallback", "com.sea.base.ext.view.UIContextExtKt.addBackPressedCallback"))
    override fun onBackPressed() {
        super.onBackPressed()
    }

    /**
     * 是否开启参数自动绑定
     */
    protected open fun openAutoBindParams(): Boolean = true

    /**
     * 是否支持activity被杀死后重建（是否使用 savedInstanceState中相关数据，
     * 系统默认在其中保存了Fragment的状态，重建会导致fragment异常展示）
     *
     * 注意：此处仅限于app杀死重建，对于fragment的内部的重建参考：[BaseKtFragment.onCreate]
     *
     * @return 默认不支持。如果返回true，则必须测试杀死后重建的流程
     */
    protected open fun supportRebuildData() = false

    /**
     * 建议：
     * view初始化
     * 事件点击
     * 基本设置
     */
    protected abstract fun init(savedInstanceState: Bundle?)

    /**
     * 建议：
     * 订阅viewModel的数据并进行绑定
     * 调用数据加载
     */
    protected abstract fun bindData()

    protected abstract fun onPagerBindViewPrepare()

    /////////////////////////////////////////////////////////////////////////////////////////////////
    // IUIContext的实现
    /////////////////////////////////////////////////////////////////////////////////////////////////

    override val isFinished: Boolean get() = isFinishing
    override val currentFragmentManager get() = supportFragmentManager
    override val rootView get() = window?.decorView
    override val realDelegate get() = this

    override fun requireViewLifecycle() = lifecycle

    override fun viewLifecycleWithCallback(run: (Lifecycle?) -> Unit) {
        run.invoke(lifecycle)
    }

    override fun getActivity() = this

    override fun getContext() = this
}